package com.example.aijiancece.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.example.aijiancece.DetectionResultActivity;
import com.example.aijiancece.R;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.example.aijiancece.api.SparkApiManager;
import com.example.aijiancece.database.entity.HistoryEntity;

public class HomeFragment extends Fragment {

    private TextInputEditText etUrl;
    private TextInputEditText etContent;
    private SparkApiManager apiManager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        etUrl = view.findViewById(R.id.etUrl);
        etContent = view.findViewById(R.id.etContent);
        MaterialButton btnCheck = view.findViewById(R.id.btnCheck);
        MaterialButton btnUpload = view.findViewById(R.id.btnUpload);

        apiManager = new SparkApiManager();
        apiManager.setOnResponseListener(new SparkApiManager.OnResponseListener() {
            @Override
            public void onSuccess(String response) {
                requireActivity().runOnUiThread(() -> {
                    String[] parts = response.split("\n\n");
                    String result = parts[0];
                    String analysis = parts.length > 1 ? parts[1] : "";
                    String checkContent = etUrl.getText().toString().trim();
                    String checkText = etContent.getText().toString().trim();
                    showDetectionResult(
                            checkContent.isEmpty() ? checkText : checkContent,
                            result,
                            analysis
                    );
                });
            }

            @Override
            public void onError(String error) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireContext(), "检测失败：" + error, Toast.LENGTH_SHORT).show();
                });
            }
        });

        btnCheck.setOnClickListener(v -> checkContent());
        btnUpload.setOnClickListener(v -> uploadFile());
    }

    private void checkContent() {
        String url = etUrl.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if (url.isEmpty() && content.isEmpty()) {
            Toast.makeText(requireContext(), "请输入网址或内容", Toast.LENGTH_SHORT).show();
            return;
        }

        String checkContent = url.isEmpty() ? content : url;
        apiManager.detectContent(checkContent);
    }

    private void uploadFile() {
        // TODO: 实现文件上传功能
        Toast.makeText(requireContext(), "文件上传功能开发中", Toast.LENGTH_SHORT).show();
    }

    private void showDetectionResult(String content, String result, String analysis) {
        Intent intent = new Intent(requireContext(), DetectionResultActivity.class);
        intent.putExtra(DetectionResultActivity.EXTRA_CONTENT, content);
        intent.putExtra(DetectionResultActivity.EXTRA_RESULT, result);
        intent.putExtra(DetectionResultActivity.EXTRA_ANALYSIS, analysis);
        startActivity(intent);
        requireActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void startDetection() {
        String url = etUrl.getText().toString().trim();
        String content = etContent.getText().toString().trim();

        if (url.isEmpty() && content.isEmpty()) {
            Toast.makeText(requireContext(), "请输入网址或内容", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存历史记录
        HistoryEntity history = new HistoryEntity(
                url.isEmpty() ? content : url,
                "", // result 将在检测完成后更新
                "", // analysis 将在检测完成后更新
                System.currentTimeMillis()
        );
        // ...其他代码
    }
} 